package com.zsc.yadada.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zsc.yadada.annotation.AuthCheck;
import com.zsc.yadada.common.BaseResponse;
import com.zsc.yadada.common.DeleteRequest;
import com.zsc.yadada.common.ErrorCode;
import com.zsc.yadada.common.ResultUtils;
import com.zsc.yadada.constant.UserConstant;
import com.zsc.yadada.exception.BusinessException;
import com.zsc.yadada.exception.ThrowUtils;
import com.zsc.yadada.model.dto.app.AppAddRequest;
import com.zsc.yadada.model.dto.app.AppEditRequest;
import com.zsc.yadada.model.dto.app.AppQueryRequest;
import com.zsc.yadada.model.dto.app.AppUpdateRequest;
import com.zsc.yadada.model.entity.App;
import com.zsc.yadada.model.entity.User;
import com.zsc.yadada.model.enums.ReviewStatusEnum;
import com.zsc.yadada.model.vo.AppVO;
import com.zsc.yadada.service.AppService;
import com.zsc.yadada.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/app")
public class AppController {

    @Resource
    private UserService userService;

    @Resource
    private AppService appService;

    /**
     * 创建应用
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> CreateApp(@RequestBody AppAddRequest appAddRequest, HttpServletRequest request){
        if(appAddRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        App app = new App();
        BeanUtils.copyProperties(appAddRequest,app);

        //参数判断
        appService.validApp(app,true);

        User loginUser = userService.getLoginUser(request);
        app.setUserId(loginUser.getId());

        //写入数据库
        boolean result = appService.save(app);
        if(!result){
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }

        Long id = app.getId();
        return ResultUtils.success(id);
    }

    /**
     * 删除应用
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> DeleteApp(@RequestBody DeleteRequest deleteRequest,HttpServletRequest request){
        if(deleteRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = appService.deleteApp(deleteRequest,loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 更新应用
     * @param appUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE) //标记这个接口只能给管理员使用
    public BaseResponse<Boolean> UpdateApp(@RequestBody AppUpdateRequest appUpdateRequest){
        if(appUpdateRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = appService.updateApp(appUpdateRequest);
        return ResultUtils.success(result);
    }

    /**
     * 根据id获取应用
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<AppVO> GetAppById(Long id){
        if(id == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        AppVO appVO = appService.getAppById(id);
        return ResultUtils.success(appVO);
    }

    /**
     * 分页获取应用列表（仅管理员可用）
     * @param appQueryRequest
     * @return
     */
    @GetMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE) //标记这个接口只能给管理员使用
    public BaseResponse<Page<App>> ListAppByPage(@RequestBody AppQueryRequest appQueryRequest){
        if(appQueryRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = 1;
        long size = 10;

        Page<App> page = appService.page(new Page<>(current, size), appService.getQueryWrapper(appQueryRequest));
        return ResultUtils.success(page);
    }

    /**
     * 分页获取应用列表
     * @param appQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<AppVO>> listAppVOByPage(@RequestBody AppQueryRequest appQueryRequest,HttpServletRequest request){
        long current = appQueryRequest.getCurrent();
        long size = appQueryRequest.getPageSize();
        // 限制爬虫
        if(size > 20){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 只能看到已过审的应用
        appQueryRequest.setReviewStatus(ReviewStatusEnum.PASS.getValue());
        // 查询数据库
        Page<App> appPage = appService.page(new Page<>(current, size),
                appService.getQueryWrapper(appQueryRequest));
        // 获取封装类
        return ResultUtils.success(appService.getAppVOPage(appPage, request));
    }

    /**
     * 分页获取当前登录用户创建的应用列表
     *
     * @param appQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<AppVO>> listMyAppVOByPage(@RequestBody AppQueryRequest appQueryRequest,
                                                       HttpServletRequest request) {
        ThrowUtils.throwIf(appQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        appQueryRequest.setUserId(loginUser.getId());
        long current = appQueryRequest.getCurrent();
        long size = appQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<App> appPage = appService.page(new Page<>(current, size),
                appService.getQueryWrapper(appQueryRequest));
        // 获取封装类
        return ResultUtils.success(appService.getAppVOPage(appPage, request));
    }

    /**
     * 编辑应用（给用户使用）
     *
     * @param appEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editApp(@RequestBody AppEditRequest appEditRequest, HttpServletRequest request) {
        if (appEditRequest == null || appEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        App app = new App();
        BeanUtils.copyProperties(appEditRequest, app);
        // 数据校验
        appService.validApp(app, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = appEditRequest.getId();
        App oldApp = appService.getById(id);
        ThrowUtils.throwIf(oldApp == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldApp.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 重置审核状态
        app.setReviewStatus(ReviewStatusEnum.REVIEWING.getValue());
        // 操作数据库
        boolean result = appService.updateById(app);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }




}
